<template>
  <div v-loading="loading" class="home-container flex min-w-940px">
    <header-component />
    <div class="main">
      <div class="home full select-none flex flex-col items-center justify-between">
        <div class="head">
          <div class="search">
            <el-icon>
              <search />
            </el-icon>
            <div class="search-center">
              <el-input
                v-model="queryParams.title"
                :bordered="false"
                clearable
                placeholder="请输入会议名称进行搜索"
                @clear="clearData"
                @keyup.enter="fetchData"
              />
            </div>
            <div class="search-right" style="display: flex; align-items: center">
              <el-select v-model="queryParams.type" class="type-select" clearable placeholder="会议类型" @change="handleTypeChange">
                <el-option label="全部" value="" />
                <el-option label="人大会议" value="1" />
                <el-option label="政协会议" value="2" />
                <el-option label="普通会议" value="3" />
              </el-select>
              <el-button :icon="Search" round type="primary" @click="handleSearch">
                <span style="margin-left: -1px; letter-spacing: 2px">搜索</span>
              </el-button>
            </div>
          </div>

          <div class="head_add">
            <el-button round type="primary" @click="((isEditMode = false), (showFormDialog = true))">预约会议</el-button>
          </div>
        </div>

        <!-- 活动 -->
        <div class="warp flex-1 flex-col flex">
          <div v-if="list.length > 0" class="list flex flex-wrap">
            <template v-for="item in list" :key="item.id">
              <list-item
                class="meeting-card"
                :item="item"
                @active-config="activeConfig"
                @active-edit="handleEdit"
                @handle-delete="handleDelete"
                @toggle-open-status="handleToggleOpenStatus"
              />
            </template>
          </div>
          <el-empty v-else class="vab-data-empty" description="暂无数据" />
          <div class="bottom_pagination">
            <el-pagination
              v-model:current-page="queryParams.page"
              :background="true"
              layout="total, prev, pager, next"
              :page-size="queryParams.limit"
              :total="total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 表单弹窗 -->
    <el-dialog v-model="showFormDialog" append-to-body destroy-on-close :title="isEditMode ? '编辑会议' : '预约会议'" width="900px">
      <meeting-form :initial-data="form" :is-edit="isEditMode" @cancel="showFormDialog = false" @submit="handleFormSubmit" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { nextTick } from 'vue'
import Public from '~/src/api/public/index.ts'
import router from '~/src/router'
import HeaderComponent from '../components/header.vue'
import ListItem from './components/ListItem.vue'
import MeetingForm from './components/MeetingForm.vue'
import type { Meeting } from './config.ts'
import { moduleApi } from './config.ts'
import { useRoutesStore } from '/@/store/modules/routes'
import { saveActivityInfo } from '/@/utils/activityHelper'

const queryParams = reactive({
  page: 1,
  limit: 12,
  type: '',
  title: '',
})
const form = ref<Meeting>({})
const { setRoutes } = useRoutesStore()
const loading = ref(false)
const total = ref(0)
const activeConfig = async (id: any, signUpType: any, title: any) => {
  saveActivityInfo(id, signUpType, title)
  try {
    // 确保路由已经加载
    await setRoutes('intelligence')

    // 添加延迟确保路由注册完成
    await nextTick()

    // 尝试名称路由，如果失败则降级到路径路由
    await router.push({ path: '/meeting/agenda' })
  } catch (error) {
    console.error('路由跳转失败:', error)
    ElMessage.error('路由跳转失败，请刷新页面后重试')
  }
}
const isEditMode = ref(false)

// 控制表单弹窗显示
const showFormDialog = ref(false)
interface ApiResponse<T> {
  code: number
  result: T
}

// 表格数据
const list = ref<Meeting[]>([])

// 加载状态
const listLoading = ref<boolean>(true)
onActivated(() => {
  fetchData()
})

onMounted(async () => {
  await fetchData()
})

// 表单提交处理
const handleFormSubmit = async (formData: Meeting) => {
  console.log('表单提交的数据:', formData)
  console.log('isEditMode', isEditMode.value)
  try {
    let response
    if (isEditMode.value) {
      // 检查编辑模式下是否有id字段
      if (!formData.id) {
        ElMessage.error('编辑会议时缺少ID字段')
        return
      }
      response = await Public.editApi({ url: moduleApi, data: formData })
    } else {
      response = await Public.addApi({ url: moduleApi, data: formData })
    }

    if (response.code === -1) {
      ElMessage.error(response.message || '时间冲突')
      return
    }

    if (response.code === 0) {
      ElMessage.success(isEditMode.value ? '修改成功' : '预约成功')
      showFormDialog.value = false
      fetchData() // 重新获取数据
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}
const fetchData = async () => {
  listLoading.value = true
  try {
    const response = await Public.getDetailApi({ url: moduleApi, params: queryParams })
    const { code, result } = response as unknown as ApiResponse<{ rows: Meeting[]; count: number }>
    if (code === 0) {
      list.value = result.rows // 正确
      total.value = result.count // 正确
    }
  } catch (error) {
    console.error('请求失败:', error)
  } finally {
    listLoading.value = false
  }
}
/** 创建会议 */

/** 删除 */

// 删除行数据
const handleDelete = (id: Meeting) => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 这里可以添加删除逻辑
        await Public.delApi({ url: moduleApi, id })
      } catch (error) {
        console.error('删除失败:', error)
      } finally {
        fetchData()
        ElMessage({
          type: 'success',
          message: '删除成功!',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

/** 搜索 */
const handleSearch = async () => {
  await fetchData()
}
/** 清空搜索 */
const clearData = async () => {
  queryParams.title = ''
  queryParams.type = ''
  await fetchData()
}

const handleCurrentChange = (val: number) => {
  queryParams.page = val
  fetchData()
}
const handleSizeChange = (val: number) => {
  queryParams.limit = val
  fetchData()
}

/** 会议类型变化处理 */
const handleTypeChange = async () => {
  await fetchData()
}

const handleEdit = (row: Meeting) => {
  // 将当前行数据赋值给 form
  form.value = { ...row }
  showFormDialog.value = true
  isEditMode.value = true
}

// 处理会议开放状态切换
const handleToggleOpenStatus = async (data: { id: string; isOpen: boolean }) => {
  try {
    loading.value = true
    const response = await Public.editApi({
      url: moduleApi,
      data: {
        id: data.id,
        isOpen: data.isOpen,
      },
    })

    if (response.code === 0) {
      ElMessage.success(`会议已${data.isOpen ? '开放' : '关闭'}`)
      // 更新本地列表中的状态
      const meetingIndex = list.value.findIndex((item) => item.id === data.id)
      if (meetingIndex !== -1) {
        list.value[meetingIndex].isOpen = data.isOpen
      }
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('更新会议开放状态失败:', error)
    ElMessage.error('更新失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.home-container {
  width: 100vw;
  height: 100%;
  background: url('https://qushen-file.oss-cn-beijing.aliyuncs.com/outsourcing-2023/zhi-hui/admin/home_bg.png') no-repeat;
  background-size: 100% 100%;

  .main {
    width: 100%;
    height: 100%;
    overflow: auto;
  }

  .home {
    box-sizing: border-box;
    padding-top: 50px;
    margin: auto;

    .head {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 40px auto 10px auto;

      .search {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0px 4px 0px 20px;
        background-color: #fff;
        border-radius: 20px;

        .search-center {
          width: 500px;
          height: 40px;
          line-height: 40px;
          background: #fff;
          :deep(.el-input__wrapper) {
            border: none !important;
            box-shadow: none !important;
          }
        }

        .search-right {
          display: flex;
          align-items: center;
          :deep(.el-select) {
            .el-input {
              .el-input__wrapper {
                padding-left: 0;
                border: none !important;
                box-shadow: none !important;
              }
            }
          }

          .type-select {
            width: 120px;
            margin-right: 10px;
          }
        }
      }

      .head_add {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        margin-left: 20px;
      }
    }

    // 页面标题样式
    .page-title {
      width: 95%;
      max-width: 1600px;
      margin: 10px auto 0;
      text-align: left;

      h2 {
        margin-bottom: 5px;
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }

      .title-desc {
        margin-bottom: 10px;
        font-size: 14px;
        color: #909399;
      }
    }

    // 会议卡片样式
    .meeting-card {
      margin: 15px;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        transform: translateY(-5px);
      }
    }

    .warp {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;
      border-radius: 10px;
    }

    .list {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      justify-content: center;
      width: 100%;
      max-width: 1600px;
      margin: 0 auto;
    }

    // 小屏幕设备 (小于1366px)
    @media screen and (max-width: 1365px) {
      .warp {
        padding: 15px 10px;
      }

      .list {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 15px;
        width: 95%;
        max-width: 1000px;
        margin: 0 auto;
      }
    }

    // 中等屏幕设备 (1366px - 1739px)
    @media screen and (min-width: 1366px) and (max-width: 1739px) {
      .warp {
        padding: 15px;
      }

      .list {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 20px;
        width: 95%;
        max-width: 1200px;
        margin: 0 auto;
      }
    }

    // 大屏幕设备 (大于或等于1740px)
    @media screen and (min-width: 1740px) {
      .warp {
        padding: 20px;
      }

      .list {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 25px;
        width: 95%;
        max-width: 1600px;
        margin: 0 auto;
      }
    }
  }
}

.footer {
  width: 100%;
  margin-top: 10px;
  text-align: center;
  border-top: 1px #bcbec1 solid;
}

:deep() {
  .el-button-group .el-button--primary:first-child {
    display: none;
  }
  .el-dropdown .el-dropdown__caret-button {
    width: auto;
    margin-left: 5px;
    background-color: var(--el-button-hover-bg-color);
    border: 0;
  }
  .el-button:hover {
    .el-dropdown .el-dropdown__caret-button {
      background-color: #7fa9f3;
    }
  }

  .el-dropdown .el-dropdown__caret-button.el-button::before {
    background: none;
  }
  .el-dropdown .el-dropdown__caret-button::before {
    background: none;
  }
}
</style>

<style lang="scss">
.search {
  .search-center {
    :deep(.el-input__wrapper) {
      background-color: transparent !important;
      border: none !important;
      box-shadow: none !important;
    }
  }

  .search-right {
    .el-select__wrapper {
      position: relative;
      box-sizing: border-box;
      display: flex;
      gap: 6px;
      align-items: center;
      min-height: 32px;
      padding: 4px 12px;
      font-size: 14px;
      line-height: 24px;
      text-align: left;
      cursor: pointer;
      background-color: transparent !important;
      border: none !important;
      box-shadow: none !important;
      transition: var(--el-transition-duration);
      transform: translate3d(0, 0, 0);
    }

    .type-select {
      width: 120px;
      margin-right: 10px;
    }
  }
}
</style>
